<template>
  <el-form ref="loginForm"
           :rules="loginRules"
           :model="loginForm"
           class="login-form"
           status-icon
           label-width="0">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username"
                size="small"
                auto-complete="off"
                :placeholder="$t('login.pleaseUser')"
                @keyup.enter.native="handleLogin">
        <i slot="prefix"
           class="icon-yonghu" />
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input :type="passwordType"
                v-model="loginForm.password"
                size="small"
                auto-complete="off"
                :placeholder="$t('login.pleasePass')"
                @keyup.enter.native="handleLogin">
        <i slot="suffix"
           class="el-icon-view el-input__icon"
           @click="showPassword" />
        <i slot="prefix"
           class="icon-lock" />
      </el-input>
    </el-form-item>
    <el-form-item prop="code">
      <el-row :span="24">
        <el-col :span="16">
          <el-input :maxlength="code.len"
                    v-model="loginForm.code"
                    size="small"
                    auto-complete="off"
                    :placeholder="$t('login.pleaseCode')"
                    @keyup.enter.native="handleLogin">
            <i slot="prefix"
               class="icon-yanzhengma" />
          </el-input>
        </el-col>
        <el-col :span="8">
          <div class="login-code">
            <span v-if="code.type == 'text'"
                  class="login-code-img"
                  @click="refreshCode">{{ code.value }}</span>
            <img v-else
                 :src="code.src"
                 class="login-code-img"
                 @click="refreshCode">
            <!-- <i class="icon-shuaxin login-code-icon" @click="refreshCode"></i> -->
          </div>
        </el-col>
      </el-row>

    </el-form-item>
    <el-form-item>
      <el-button type="primary"
                 size="small"
                 class="login-submit"
                 @click.native.prevent="handleLogin">{{$t('login.logOn')}}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { randomLenNum } from '../../util/util'
import { mapGetters } from 'vuex'
import { setLang } from '../../api/admin/dict'
import { getStore } from '../../util/store'


export default {
  name: 'Userlogin',
  data () {
    return {
      socialForm: {
        code: '',
        state: ''
      },
      loginForm: {
        username: this.supper ? 'superadmin' : '',
        password: '',
        code: '',
        redomStr: ''
      },
      checked: false,
      code: {
        src: '/code',
        value: '',
        len: 4,
        type: 'image'
      },
      loginRules: {
        username: [
          { required: true, message: this.$t('login.pleaseUser'), trigger: 'blur' }
        ],
        password: [
          { required: true, message: this.$t('login.pleasePass'), trigger: 'blur' },
          { min: 6, message: this.$t('login.lessSixLength'), trigger: 'blur' }
        ],
        code: [
          { required: true, message: this.$t('login.pleaseCode'), trigger: 'blur' },
          { min: 4, max: 4, message: this.$t('login.codeLessForLength'), trigger: 'blur' }
        ]
      },
      passwordType: 'password'
    }
  },
  created () {
    this.refreshCode()
  },
  mounted () {
  },
  computed: {
    ...mapGetters(['tagWel'])
  },
  props: ['supper'],
  methods: {
    refreshCode () {
      this.loginForm.code = ''
      this.loginForm.randomStr = randomLenNum(this.code.len, true)
      this.code.type === 'text'
        ? (this.code.value = randomLenNum(this.code.len))
        : (this.code.src = `${this.codeUrl}?randomStr=${this.loginForm.randomStr}`)
    },
    showPassword () {
      this.passwordType == ''
        ? (this.passwordType = 'password')
        : (this.passwordType = '')
    },
    handleLogin () {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          let language = getStore({ name: 'language' })
          setLang('/admin', language, this.loginForm.username + '$' + getStore({ name: 'orgId' })).then(res => {
            this.$i18n.locale = language;
            this.$store.commit("SET_LANGUAGE", language);
            if (this.supper) {
              this.$store.dispatch('loginSuperUser', this.loginForm).then(() => {
                this.$store.dispatch('GetUserInfo').then(() => {
                  // this.$router.push({ path: this.tagWel.value })
                  this.$router.push({ path: '/workbench' })
                }).catch((res) => {
                  /* 许可证过期唯一标识：license_invalid（License expired ），跳转激活页面
                     许可证锁定唯一标识：license_locked（License locked），跳转登录页面  */
                  // 判断许可证是否激活/过期/锁定
                  if (String(res).indexOf('License expired') > -1) {
                    this.$store.dispatch('FedLogOut').then(() => {
                      this.$router.push({ path: '/licenseActive' })
                    })
                  } else if (String(res).indexOf('License locked') > -1) {
                    this.$store.dispatch('FedLogOut').then(() => {
                      this.$router.push({ path: '/login' })
                    })
                  } else {
                    this.$store.dispatch('FedLogOut').then(() => {
                      this.$router.push({ path: '/login' })
                    })
                  }
                })
              }).catch(() => {
                this.refreshCode()
              })
            } else {
              this.$store.dispatch('LoginByUsername', this.loginForm).then(() => {
                this.$store.dispatch('GetUserInfo').then(() => {
                  // this.$router.push({ path: this.tagWel.value })
                  this.$router.push({ path: '/workbench' })
                }).catch((res) => {
                  /* 许可证过期唯一标识：license_invalid（License expired ），跳转激活页面
                     许可证锁定唯一标识：license_locked（License locked），跳转登录页面  */
                  // 判断许可证是否激活/过期/锁定
                  if (String(res).indexOf('License expired') > -1) {
                    this.$store.dispatch('FedLogOut').then(() => {
                      this.$router.push({ path: '/licenseActive' })
                    })
                  } else if (String(res).indexOf('License locked') > -1) {
                    this.$store.dispatch('FedLogOut').then(() => {
                      this.$router.push({ path: '/login' })
                    })
                  } else {
                    this.$store.dispatch('FedLogOut').then(() => {
                      this.$router.push({ path: '/login' })
                    })
                  }
                })
              }).catch(() => {
                this.refreshCode()
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style>
</style>
